package cn.stronglink.assetmanage.business.inspection.view.PatrolDetail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.UserManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Scaner.rfid.IRfidListener;
import Scaner.rfid.TimerRfidScaner;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inspection.adapter.PatrolOrderAdapter;
import cn.stronglink.assetmanage.business.task.model.ITaskSyncListener;
import cn.stronglink.assetmanage.business.task.model.OrderType;
import cn.stronglink.assetmanage.business.task.model.TaskSyncModel;
import cn.stronglink.assetmanage.dao.AssetDao;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.PatrolDao;
import cn.stronglink.assetmanage.dao.PatrolDetailDao;
import cn.stronglink.assetmanage.dao.RoomDao;
import cn.stronglink.assetmanage.dao.SearchAssetDao;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Task;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.patrol.PatrolService;
import cn.stronglink.netrequest.business.search.SearchService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by zhengjinglan on 2018/6/22.
 */

public class PatrolDetailFragment extends Fragment implements KeyEvent.Callback {
    protected Activity mActivity;
    private TextView tvPatrolOrderId;   //巡检单号
    private TextView tvPatrolLocation;  //位置
    private TextView tvOpreationUser;   //操作人
    private TextView tvOpreationTime;   //操作日期
    private Button butSacnQR, butScanRFID;
    private TimerInfraraedScaner scaner;
    private TimerRfidScaner rfidScaner;
    private ExpandableListView rv_patrol_detail_list;
    private List<Room> roomList;
    private List<String> patrolGroupNameList;   //巡检商品的组名称
    private PatrolOrderAdapter orderAdapter;    //订单详情的Adapter
    private Patrol patrol;  //巡检信息实体
    private Map<String, PatrolDetail> patrolNormalMap = new HashMap<>();    //巡检到的商品
    private Map<String, SearchAsset> searchAssetRfidMap = new HashMap<>();      //根据rfid获取资产详情
    private Map<String, SearchAsset> searchAssetSnMap = new HashMap<>();        //根据sn获取资产详情
    private List<PatrolDetail> prodetailList;  //待保存数据
    private Dialog mDialog;
    private MainActivity activity;
    private TextView txt_title_left, txt_title_right, txt_main_title;
    private Handler handler;
    private View view;

    /**
     * 去掉字符串中\R等
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = PatrolDetailFragment.this.getActivity();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_patrol_detail, container, false);
        try {
            initView(view);
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    showProgressDialog("正在加载数据");
                    initData();
                }
            };
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();
                    new Handler().post(runnable);
                    Looper.loop();
                }
            }.start();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (this.rfidScaner != null) {
            this.rfidScaner.StopSearch();
            this.rfidScaner.Destory();
        }

        if (this.scaner != null) {
            this.scaner.stop();
            this.scaner.destory();
        }
        patrolNormalMap.clear();
        searchAssetRfidMap.clear();
        searchAssetSnMap.clear();
    }

    private void initView(View view) {
        if (this.patrol == null) {
            return;
        }
        prodetailList = new ArrayList<>();
        activity = (MainActivity) this.getActivity();
        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.VISIBLE);
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.GONE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("巡检详情");
        this.tvPatrolOrderId = view.findViewById(R.id.tv_patroluncount_order_name);
        this.tvPatrolOrderId.setText(this.patrol.getId_());
        this.tvPatrolLocation = view.findViewById(R.id.tv_patrol_location);


        this.tvOpreationUser = view.findViewById(R.id.tv_patroluncount_operation_user);
        this.tvOpreationUser.setText(User.getInstance().getName());
        this.tvOpreationTime = view.findViewById(R.id.tv_patroluncount_operation_date);
        final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.tvOpreationTime.setText(format.format(new Date()));

        //加载资产列表
        this.patrolGroupNameList = new ArrayList<>();
        this.patrolGroupNameList.add(getResources().getString(R.string.patrol_count));
        this.orderAdapter = new PatrolOrderAdapter(getActivity(), patrolGroupNameList);
        this.rv_patrol_detail_list = view.findViewById(R.id.rv_patrol_detail_list);
        this.rv_patrol_detail_list.setAdapter(this.orderAdapter);
        this.rv_patrol_detail_list.expandGroup(0);
        if (roomList != null && roomList.size() > 0) {

            this.tvPatrolLocation.setText(roomList.get(0).getName());
        }
        this.loadDataToAdapter();   //将数据加载到adapter

        rv_patrol_detail_list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                PatrolDetail data = (PatrolDetail) orderAdapter.getChild(groupPosition, childPosition);
                String searchAssetId = null;
                if (data.getSerialNo() != null) {
                    searchAssetId = data.getSerialNo();
                } else if (data.getRfidNo() != null) {
                    searchAssetId = searchAssesByRfid(data.getRfidNo());
                }
                if (searchAssetId != null) {
                    showOrderByPosition(searchAssetId);
                }
                return false;
            }
        });
        //初始化条码扫描按钮
        this.butSacnQR = view.findViewById(R.id.btn_patrol_detail_qr);  //扫描条码按钮
        this.butSacnQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PatrolDetailFragment.this.scaner.playSingle();
            }
        });

        //初始化rfid扫描按钮
        this.butScanRFID = view.findViewById(R.id.btn_patrol_detail_rfid);
        this.butScanRFID.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PatrolDetailFragment.this.switchRfidScan();
            }
        });

        //初始化条码扫描模块
        this.scaner = new TimerInfraraedScaner(this.getContext());
        this.scaner.setScanerListener(new IScanerListener() {
            @Override
            public void onScaning(List<String> data) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.size(); i++) {
                    sb.append(data.get(i) + "   ");
                    String sn = data.get(i).replace(" ", "");
                    PatrolDetailFragment.this.pushSn(sn);

                }
                Log.i("========", sb.toString());
            }
        });

        //初始化rfid扫描模块
        this.rfidScaner = new TimerRfidScaner(this.getContext());
        this.rfidScaner.setRfidListener(new IRfidListener() {
            @Override
            public void onRfiding(List<TimerRfidScaner.EpcDataBase> data) {
                StringBuilder sb = new StringBuilder();

                String rfid = data.get(data.size() - 1).toString().replace(" ", "");
                PatrolDetailFragment.this.pushRfid(rfid);
                Log.i("========", sb.toString());
            }

            @Override
            public void onSet() {

            }

            @Override
            public void getException(String msg) {
                Toast.makeText(PatrolDetailFragment.this.getContext(), "错误", Toast.LENGTH_LONG).show();
            }
        });

        //巡检按钮
        final Button butPatrolFinish = view.findViewById(R.id.btn_patrol_detail_finish);
        butPatrolFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    //todo:判断是否离线

                    // 1.自动 2.离线
                    SyncTypes syncType = DaoManager.getDaoSession(getContext()).getSyncTypesDao()
                            .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
                    int tp = 0;
                    if (syncType != null) {
                        tp = syncType.getSyscTs();
                    }
                    if (tp == 1) {

                        savePatrolWeb();


                    } else {
                        savePatrolData();
                        butPatrolFinish.setEnabled(false);
                        mActivity.onBackPressed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.toastShort(e.getMessage());
                }


            }
        });
        hideProgressDialog();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            Toast.makeText(this.getContext(), "传递的巡检单参数为空，无法正常巡检", Toast.LENGTH_SHORT).show();
            return;
        }

        String patrolOrderId = bundle.getString(Constants.PATROL_DETAIL_NO);
        if (patrolOrderId == null || patrolOrderId.isEmpty()) {
            Toast.makeText(this.getContext(), "传递的巡检编号为空，无法正常巡检", Toast.LENGTH_LONG).show();
            return;
        }

        //获取巡检单信息
        this.patrol = DaoManager.getDaoSession(getContext()).getPatrolDao().queryBuilder().where(
                PatrolDao.Properties.Id_.eq(patrolOrderId)
        ).unique();

        //获取巡检中的资产详情
        prodetailList = DaoManager.getDaoSession(getContext()).getPatrolDetailDao().queryBuilder().where(
                PatrolDetailDao.Properties.OrderNo.eq(patrolOrderId)
        ).list();

        //将巡检详情遍历到Map中，便于快速查找
        for (int i = 0; i < prodetailList.size(); i++) {
            PatrolDetail detail = prodetailList.get(i);

            patrolNormalMap.put(detail.getSerialNo(), detail);
        }
        List<SearchAsset> searchAssetList = DaoManager
                .getDaoSession(getContext()).getSearchAssetDao().queryBuilder().list();
        //将巡检资产详情遍历到Map中，便于快速查找
        for (int i = 0; i < searchAssetList.size(); i++) {
            SearchAsset searchAsset = searchAssetList.get(i);
            if (searchAsset.getRfidNo() != null) {
                searchAssetRfidMap.put(searchAsset.getRfidNo(), searchAsset);
            }
            if (searchAsset.getSerialNo() != null) {
                searchAssetSnMap.put(searchAsset.getSerialNo(), searchAsset);
            }

        }
        //通过id查询地点
        roomList = DaoManager
                .getDaoSession(MyApplication.APP_CONTEXT).getRoomDao().queryBuilder()
                .where(RoomDao.Properties.Id_.eq(patrol.getRoomId_())).list();

        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                initView(view);

            }
        });


    }

    /**
     * 推送扫到的rfid到指定列表
     *
     * @param rfid
     */
    private void pushRfid(String rfid) {
        rfid = replaceBlank(rfid);

        if (searchAssetRfidMap.containsKey(rfid)) {
            PatrolDetail goods = createPatrolProfitGoods(this.patrol.getId_(), rfid);//创建巡检资产
            SearchAsset searchAsset = searchAssetRfidMap.get(rfid);
            goods = setPatrolDetailData(searchAsset, goods);
            String sn = searchAsset.getSerialNo();
            if (!patrolNormalMap.containsKey(sn)) {
                patrolNormalMap.put(sn, goods);   //将巡检资产放到巡检缓存列表
                DaoManager.getDaoSession(getContext()).getPatrolDetailDao().insert(goods);//将资产保存到数据库
                //在界面中显示刚刚刷到的资产

                final PatrolDetail finalGoods = goods;
                this.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((List<PatrolDetail>) orderAdapter.getGroup(0)).add(0, finalGoods); // 向巡检UI列表中添加资产信息
                        orderAdapter.notifyDataSetChanged();  // 刷新列表
                    }
                });
            }
        }
    }

    private void pushSn(String sn) {
        sn = replaceBlank(sn);


        if (searchAssetSnMap.containsKey(sn)) {
            if (!patrolNormalMap.containsKey(sn)) {
                PatrolDetail goods = createPatrolProfitGoodsSn(this.patrol.getId_(), sn);    //创建巡检资产
                SearchAsset searchAsset = searchAssetSnMap.get(sn);
                goods = setPatrolDetailData(searchAsset, goods);

                patrolNormalMap.put(sn, goods); //将巡检资产放到巡检缓存列表
                DaoManager.getDaoSession(getContext()).getPatrolDetailDao().insertOrReplace(goods);//将资产保存到数据库
                //在界面中显示刚刚刷到的资产
                final PatrolDetail finalGoods = goods;
                this.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((List<PatrolDetail>) orderAdapter.getGroup(0)).add(0, finalGoods); // 向巡检UI列表中添加资产信息
                        orderAdapter.notifyDataSetChanged();  // 刷新列表
                    }
                });
            }
        } else if (searchAssetRfidMap.containsKey(sn)) {
            SearchAsset searchAsset = searchAssetRfidMap.get(sn);
            sn = searchAsset.getSerialNo();
            if (!patrolNormalMap.containsKey(sn)) {
                PatrolDetail goods = createPatrolProfitGoodsRfid(this.patrol.getId_(), sn);    //创建巡检资产
                goods = setPatrolDetailData(searchAsset, goods);
                patrolNormalMap.put(sn, goods); //将巡检资产放到巡检缓存列表
                DaoManager.getDaoSession(getContext()).getPatrolDetailDao().insertOrReplace(goods);//将资产保存到数据库
                //在界面中显示刚刚刷到的资产
                final PatrolDetail finalGoods = goods;
                this.getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((List<PatrolDetail>) orderAdapter.getGroup(0)).add(0, finalGoods); // 向巡检UI列表中添加资产信息
                        orderAdapter.notifyDataSetChanged();  // 刷新列表
                    }
                });
            }

        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        // 按下F3按钮进行Rfid扫描器的开关操作
        if (keyCode == 133) {
            this.switchRfidScan();
        }
        return false;
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
        return false;
    }

    /**
     * 开启或关闭rfid扫描
     */
    private void switchRfidScan() {
        if (rfidScaner.isSearching()) {
            rfidScaner.StopSearch();
            butScanRFID.setText("开始扫RFID盘点");

        } else {
            rfidScaner.StartSearch();
            butScanRFID.setText("停止扫RFID盘点");
        }
    }

    private void loadDataToAdapter() {
        ((List<PatrolDetail>) this.orderAdapter.getGroup(0)).addAll(this.patrolNormalMap.values());
        orderAdapter.notifyDataSetChanged();    //刷新列表
        orderAdapter.onGroupExpanded(1);
    }

    public PatrolDetail createPatrolProfitGoods(String patrolOrderId, String goodsRfid) {
        PatrolDetail goods = new PatrolDetail();
        goods.setOrderNo(patrolOrderId);
        goods.setRfidNo(goodsRfid);

        return goods;
    }

    /**
     * 通过sn创建新的巡检详情
     *
     * @param patrolOrderId
     * @param sn
     * @return
     */
    public PatrolDetail createPatrolProfitGoodsSn(String patrolOrderId, String sn) {
        PatrolDetail goods = new PatrolDetail();
        goods.setOrderNo(patrolOrderId);
        goods.setSerialNo(sn);

        return goods;
    }

    public PatrolDetail createPatrolProfitGoodsRfid(String patrolOrderId, String rfid) {
        PatrolDetail goods = new PatrolDetail();
        goods.setOrderNo(patrolOrderId);
        goods.setRfidNo(rfid);

        return goods;
    }

    /**
     * 通过rfid查询是否存在Asset
     *
     * @param rfid)
     * @return
     */
    public String searchAssesByRfid(String rfid) {
        List<SearchAsset> asset = DaoManager
                .getDaoSession(MyApplication.APP_CONTEXT).getSearchAssetDao().queryBuilder().where(SearchAssetDao.Properties.RfidNo.eq(rfid))
                .list();
        if (asset != null && asset.size() > 0) {
            return asset.get(asset.size() - 1).getSerialNo();
        }
        return null;
    }

    /**
     * 跳转到资产详情页面
     *
     * @param assetId
     */
    public void showOrderByPosition(String assetId) {

        // 显示盘点详情页面

        PromissionEntity pe = new PromissionEntity();
        pe.setPosition(MainActivity.FRAGMENT_PATROL_ASSET_DETAIL_ID);

        // 设置打开巡检详情后传递的参数
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.PATROL_DETAIL_NO, assetId);
        pe.setBundle(bundle);
        activity.onEventRegister(pe);

    }

    /**
     * 将资产信息赋值给巡检详情中
     *
     * @param searchAsset
     */
    public PatrolDetail setPatrolDetailData(SearchAsset searchAsset, PatrolDetail goods) {
        if (searchAsset != null) {
            goods.setAssetName(searchAsset.getAssetName());
            goods.setAssetNo(searchAsset.getAssetNo());
            goods.setBrandId(searchAsset.getBrandId());
            goods.setBrandId_(searchAsset.getBrandId_());
            goods.setBrandName(searchAsset.getBrandName());
            goods.setBuyTime(searchAsset.getBuyTime());
            goods.setDatacenterId(searchAsset.getDatacenterId());
            goods.setDatacenterId_(searchAsset.getDatacenterId_());
            goods.setEndUser(searchAsset.getEndUser());
            goods.setId(searchAsset.getId());
            goods.setId_(searchAsset.getId_());
            goods.setManageBranchId(searchAsset.getManageBranchId());
            goods.setManageBranchId_(searchAsset.getManageBranchId_());
            goods.setModelId(searchAsset.getModelId());
            goods.setModelId_(searchAsset.getModelId_());
            goods.setModelName(searchAsset.getModelName());
            goods.setPrice(searchAsset.getPrice());
            goods.setRackId(searchAsset.getRackId());
            goods.setRackName(searchAsset.getRackName());
            goods.setRfidNo(searchAsset.getRfidNo());
            goods.setRoomId(searchAsset.getRoomId());
            goods.setRoomId_(searchAsset.getRoomId_());
            goods.setRoomName(searchAsset.getRoomName());
            goods.setSerialNo(searchAsset.getSerialNo());
            goods.setStatus(searchAsset.getStatus());
            goods.setTypeId(searchAsset.getTypeId());
            goods.setTypeId_(searchAsset.getTypeId_());
            goods.setTypeName(searchAsset.getTypeName());
            goods.setUseBranchId(searchAsset.getUseBranchId());
            goods.setUseBranchId_(searchAsset.getUseBranchId_());

        }
        return goods;
    }

    /**
     * 将巡检单保存到数据库
     */
    public void savePatrolData() {
        patrol.setStatus(Constants.STATUS_THREE);
        patrol.setDetailList(prodetailList);
        patrol.setUpdateBy(Long.parseLong(User.getInstance().getId_()));
        patrol.setUpdateTime(tvOpreationTime.getText().toString());
        DaoManager.getDaoSession(getContext()).getPatrolDao().insertOrReplace(patrol);//将巡检单保存到数据库

    }

    public void savePatrolWeb() {
        showProgressDialog("巡检单上传中");
        this.patrol.setDetailList(this.prodetailList);
        patrol.setStatus(Constants.STATUS_THREE);
        patrol.setUpdateBy(Long.parseLong(User.getInstance().getId_()));
        patrol.setUpdateTime(tvOpreationTime.getText().toString());
        TaskSyncModel taskSyncModel = new TaskSyncModel();
        taskSyncModel.setListener(new ITaskSyncListener() {
            @Override
            public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
                hideProgressDialog();
                ToastUtil.toastShort(e.getMessage());
            }

            @Override
            public void onSucces(String orderNo, OrderType orderType, int sum) {
                hideProgressDialog();
                mActivity.onBackPressed();
            }
        });
        taskSyncModel.uploadPatrol(patrol);


    }

    public void showProgressDialog(String msg) {
        mDialog = CustomProgressDialog.createLoadingDialog(getActivity(), msg);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    public void hideProgressDialog() {
        if (mDialog != null) {
            mDialog.cancel();
        }
    }
}
